//
//function onData(event) {
//    console.log(event);
//    console.log(event.get("messageTotal"));
//}

define(function (require, exports, module) {
//    require("pushlet");
//    //对pushlet的初始化，触发web.xml中的servlet。
//    PL._init();
//    //这里的监听的主题，必须在sources.properties中配置的对象中声明这个主题。
//    //sources.properties配置着事件源（EventSources），在服务器启动时会自动激活。
//    //可以通过服务器的启动记录查看得到。可以将这个文件放到WEB-INF目录下面或者classess目录下面都可以。
//    PL.joinListen("/message/test");
    require("apps/menu");
    require("bootstrap.min");
//    require("plugins/jquery.nicescroll");

//
    $(function () {
        var h = $("#wrapper").height() - 85;
        $("#page-wrapper").height(h).find("[data-id=menu]").height(h - 50);
    });

    $(window).on("resize", function(){
         $(".panel.window:visible").find(".panel-body").dialog("center");
         $(".accordion:visible").accordion("resize");
        var h = $("#wrapper").height() - 85;
        $("#page-wrapper").height(h).find("[data-id=menu]").height(h-50);
    });

//
//    $('html').niceScroll({
//        cursorcolor: "#ccc",//#CC0071 光标颜色
//        cursoropacitymax: 1, //改变不透明度非常光标处于活动状态（scrollabar“可见”状态），范围从1到0
//        touchbehavior: false, //使光标拖动滚动像在台式电脑触摸设备
//        cursorwidth: "5px", //像素光标的宽度
//        cursorborder: "0", //     游标边框css定义
//        cursorborderradius: "5px",//以像素为光标边界半径
//        autohidemode: false //是否隐藏滚动条
//    });
    $("#messagebox").prev().on("click", function(){
        messageList();
    });
//    messageTatal();
//    function messageTatal() {
//        $.getJSON(WE.contextPath + "/app/api/message/nonReadMessageTotal", {}, function (data) {
//            if (data == 0) {
//                $("#noneRead").html(data).hide()
//            } else {
//                $("#noneRead").html(data).show()
//            }
//        });
//        setTimeout(messageTatal, 1000 * 10);
//    }

    function messageList() {
        //在以下情况下触发消息查询
//        1、点击面板，缓存标识为空（消息数的属性）
//        2、点击面板，缓存标识数和实际数不一致（消息数的属性）
//        3、查看了某条消息
        var box = $("#noneRead");
        var cache = box.attr("cache");
        if (cache == undefined || cache != box.html()) {
            refresh();
        }
    }

    function getValue(item, key){
        var keys = key.split(".");
        var it = $.extend({}, item);
        for(var i= 0, l = keys.length; i<l; i++){
            if(it[keys[i]] == undefined){
                return "";
            }
            it = it[keys[i]];
        }
        return it;
    }
    function DetailPanel(title, colums){
        this.colums = colums;
        this.title = title;
    }
    DetailPanel.prototype.show = function(row){
        var config = [];
        for(var i= 0, l = this.colums.length; i < l; i++){
            if(this.colums[i].title){
                var v = this.colums[i].field;
                if(this.colums[i].formatter){
                    v = $.utils.createUUID(10);
                    row[v] = this.colums[i].formatter(getValue(row, this.colums[i].field), row);
                }
                config.push({
                    title:this.colums[i].title,
                    value: "{{{" + v + "}}}"
                })
            }
        }
        var that = this;
        var htmlTemp = Mustache.render('<table border="0" cellpadding="0" cellspacing="0" class="hydra-table">{{#.}}' +
            '<tr class="hydra-tr-bg"><td class="hydra-left">{{title}}：</td><td class="hydra-right">{{&value}}</td></tr>{{/.}}</table>'
            , config);
        htmlTemp = '<div class="hydra-table-d-wrap">' + Mustache.render(htmlTemp, row) + '</div>';
        require("jquery-easyui-1.4.1/themes/bootstrap/easyui.css");
        require("jquery-easyui-1.4.1/themes/icon.css");
        require("jquery-easyui-1.4.1/jquery.easyui.min");
        if (!this.detailDialog) {
            this.detailDialog = $('<div id="' + $.utils.createUUID(5) + '"></div>').appendTo("body");
            this.detailDialog.html(htmlTemp);
            this.detailDialog.dialog({
                width: 500,
                height: "auto",
                closed: true,
                modal: true,
                title: that.title,
                loadingMessage: '',
                buttons: [
                    {
                        text: "关闭",
                        handler: function () {
                            that.detailDialog.dialog("close");
                        }
                    }
                ]
            })
        } else {
            this.detailDialog.html(htmlTemp);
        }
        this.detailDialog.dialog("vcenter");
        this.detailDialog.dialog("open");
    };
    var detailPanel = new DetailPanel("消息详情", [
        {
            field: 'tMessage.sendTitle',
            title: '消息标题',
            width: 200,
            align: 'left'
        },
        {
            field: 'tMessage.sendContent',
            title: '消息内容',
            width: 200,
            align: 'left'
        },
        {
            field: 'tMessage.messageType',
            title: '消息类型',
            width: 100,
            align: 'left',
            formatter: function (value, rowData, rowIndex) {
                if (value == 'MESSAGE_TYPE_SYSTEM') {
                    return '系统发送';
                } else {
                    return '私信'
                }
            }
        },
        {
            field: 'tMessage.senderName',
            title: '消息来源',
            width: 100,
            align: 'left',
            formatter: function (value, rowData, rowIndex) {
                if (rowData.messageType == 'MESSAGE_TYPE_SYSTEM') {
                    return '系统';
                } else {
                    return value;
                }
            }
        },
        {
            field: 'tMessage.sendedTime',
            title: '消息发送时间',
            width: 100,
            align: 'left'
        }
    ]);

    $.ajaxSetup({
        type:"POST",
        error:function(jqXHR, textStatus, errorThrow){
            switch (jqXHR.status){
                case(500):
                    $.messager.alert("信息", "服务器异常，请稍后再试！");
                    $("body").wait("end");
                    break;
                case (404):
                    $.messager.alert("信息", "资源不存在，请联系管理员！");
                    $("body").wait("end");
                    break;
                default :
                    break;
            }
        }
    });

    function refresh() {
        var box = $("#noneRead");var messageBox = $("#messagebox")
        var template = '<li class="avatar"><a href="#">' +
            '<img src="'+ WE.contextPath +'{{userHead}}" alt=""/><div>{{tMessage.sendTitle}}</div>'+
            '<small>{{tMessage.sendedTime}}</small><span class="label label-info">NEW</span></a></li>';
        $.getJSON(WE.contextPath + "/app/api/message/nonReadMessages", {}, function (data) {
            box.attr("cache", box.html());
            require("plugins/jquery.mustache");
            messageBox.find(".avatar").hide();
            if(data.totalElements == 0){
                messageBox.find(".nonetip").show()
            }else{
                var contents = data.content;
                for(var i= 0; i < contents.length; i ++){
                    if(contents[i].tMessage.messageType == 'MESSAGE_TYPE_USER'){
                        contents[i].userHead = "/print/" + contents[i].tMessage.fromUser.userHead
                    }else{
                        contents[i].userHead = "/print/default/pic1.png";
                    }
                    var dom = $(Mustache.render(template, contents[i])).insertBefore(messageBox.find(".dropdown-menu-footer"))
                        .data("row", contents[i]).on("click", function(){
                            var row = $(this).data("row");
                            detailPanel.show(row);
                            read(row.id);
                            messageBox.find("li.avatar:hidden").eq(0).show();
                        });
                    if(i > 5){
                        dom.hide();
                    }
                }
            }
        })
    }

    function read(id){
        $.post(WE.contextPath + "/app/api/message/readMessage?random=" + Math.random(),
            {'ids[0]': id}, function(data){
                var box = $("#noneRead");
                var total = parseInt(box.html());
                total -= 1;
                box.html(total);
                if(total == 0){
                    box.hide();
                }
                refresh();
            });
    }
    $('#side-menu').jqueryAccordionMenu();
});